package com.nebula.salary.portal.config.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nebula.salary.common.constants.Const;
import com.nebula.salary.common.result.ResponseCode;
import com.nebula.salary.common.result.ServerResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;

/**
 * 当访问接口没有权限时，自定义返回结果
 *
 * @author codex
 * @since 2022-02-11
 */
@Component
@SuppressWarnings("all")
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        
        response.setCharacterEncoding(Const.DEFAULT_CHARACTER_ENCODING);
        response.setContentType(Const.CONTENT_TYPE_JSON);
        
        PrintWriter writer = response.getWriter();
    
        String message = "请求访问：{0}，未授权，无法访问";
        message = MessageFormat.format(message, request.getRequestURI());
        writer.write(new ObjectMapper().writeValueAsString(ServerResponse.createByErrorCodeMessage(ResponseCode.FORBIDDEN.getCode(), message)));
    
        writer.flush();
        writer.close();
    }
}
